import React from 'react';
import { Select, Modal, Tooltip } from 'antd';
import type { FormInstance } from 'antd/lib/form';

import Icons from '@components/Icons';
import { COMPLETELY_FILL_STYLE, COMMON_SELECT_FIELDSNAMES } from '@utils/config';

/**
 * 将返回svg字符串转成img标签可使用的src
 * @param { string | undefined } svgStr
 * @return { undefined | string } base64Str
 */
export const imgSvgSrcRender = (svgStr?: string): undefined | string => {
  if (!svgStr) return;

  return `data:image/svg+xml;base64,${btoa(svgStr)}`;
};

/** 关闭弹窗 | 抽屉时 重置表单 */
export const useResetFormOnCloseModal = ({
  form,
  openFlag
}: {
  form: FormInstance;
  openFlag: boolean;
}) => {
  const prevOpenRef = React.useRef<boolean>();

  /** 上一次的openFlag */
  const prevOpenFlag = prevOpenRef.current;

  React.useEffect(() => {
    /** 记录本次的openFlag, 作为下一次的prevOpenFlag */
    prevOpenRef.current = openFlag;
  }, [openFlag]);

  React.useEffect(() => {
    // 当 目前(弹窗|抽屉)隐藏 并且 上一次的(弹窗|抽屉)为显示状态 则清空表单
    if (!openFlag && prevOpenFlag) {
      form.resetFields();
    }
  }, [form, prevOpenFlag, openFlag]);
};

/** 表单中 Switch|Checkbox 设置非Boolean值 */
export const setOtherTypeValue = (
  /**
   * 勾选实际值
   * @default true
   */
  checkedValue: boolean | string | number = true,

  /**
   * 不勾选实际值
   * @default false
   */
  unCheckedValue: boolean | string | number = false
) => {
  return {
    /**
     * 将 value 的值转换成字段值
     * @param { any } value
     * @default false
     * @return { boolean | string | number }
     */
    getValueFromEvent: (value: any = false): boolean | string | number => {
      return value ? checkedValue : unCheckedValue;
    }
  };
};

/**
 * 通用Select
 * @param { any[] } options
 * @default []
 * @returns { JSX.Element }
 */
export const generateCommonSelect = (options: any[] = []): JSX.Element => {
  return (
    <Select
      style={COMPLETELY_FILL_STYLE}
      allowClear
      fieldNames={COMMON_SELECT_FIELDSNAMES}
      options={options}
    />
  );
};

/** 通用删除提示 */
export const generateCommonDeleteModal = ({ title = '是否确定删除?', ...rest }: any) => {
  return Modal.confirm({
    title,
    icon: <Icons type="ExclamationCircleOutlined" />,
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    ...rest
  });
};

/** 表格列通用超出省略提示 */
export const tableColumnEllipsisRender = () => {
  return {
    ellipsis: {
      showTitle: false
    },
    render: (value: any) => (
      <Tooltip
        color="white"
        placement="topLeft"
        title={<div style={{ color: 'black' }}>{value}</div>}
      >
        {value}
      </Tooltip>
    )
  };
};
